package common.inter;

import java.util.List;
import java.util.Map.Entry;

import com.jfinal.aop.Inject;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.Kv;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Record;

import common.kit.IpKits;
import model.User;
import service.LoginService;
import service.OperateLogService;
import service.UserRoleService;

/**
 * 用户登录权限拦截
 * @author phooob
 *
 */
public class AdminAuthInter implements Interceptor{

	@Inject UserRoleService userRoleService ;
	@Inject OperateLogService operateLogService ;

    @Override
    public void intercept(Invocation inv) {
        Controller controller = inv.getController();
        User loginUser = controller.getAttr(LoginService.loginUserCacheName);
        List<Record> list = userRoleService.findUserToMenu(loginUser);
        String action = inv.getActionKey();
        for (Record menu : list) {
        	String url = menu.getStr("url") ;
        	if ( (url+";").indexOf(action+";") > -1) {
        		String saveLogUrl = menu.getStr("saveLogUrl");
        		if (StrKit.notBlank(saveLogUrl) && (saveLogUrl+";").indexOf(action+";") > -1) {
        			String params = getParams(inv);
            		operateLogService.save(menu, action, params, loginUser, IpKits.getFirstIp(controller.getRequest()));
        		}
        		inv.invoke();
				return ;
			}
		}
        controller.renderJson(Ret.fail("state" , "noAuth"));
        return ;
    }

    protected String getParams(Invocation inv) {
    	Controller controller = inv.getController();
    	String method = inv.getController().getRequest().getMethod();
    	if ("POST".equals(method)) {
			return controller.getRawData() ;
		}
    	Kv kv = Kv.create();
		for (Entry<String, String[]> entity : controller.getParaMap().entrySet()) {
			if (StrKit.notBlank(entity.getValue()[0]) && !entity.getValue()[0].equals("null") ) {
				kv.set(entity.getKey(), entity.getValue()[0]);
			}
		}
		return JsonKit.toJson(kv);
	}
}
